package com.fire.security.utils.Scheduled;
import com.fire.security.domain.Device;
import com.fire.security.mapper.DeviceMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.List;

@Slf4j
@Component
public class ScheduledTaskUtils {

    @Autowired
    private DeviceMapper deviceMapper;

    // 每天执行一次
    @Scheduled(cron = "0 0 0 * * ?")
    public void updateDeviceStatus() {
        // 获取当前时间
        LocalDateTime currentTime = LocalDateTime.now();

        // 查询所有设备
        List<Device> devices = deviceMapper.queryDeviceByStatus(3);

        // 遍历设备列表
        for (Device device : devices) {
            // 获取设备的更新时间
            Date updateTime = device.getUpdateTime();

            // 将java.util.Date转换为java.time.LocalDateTime
            LocalDateTime updateDateTime = LocalDateTime.ofInstant(updateTime.toInstant(), ZoneId.systemDefault());


            // 计算当前时间与设备更新时间相差的月数
            long monthsBetween = ChronoUnit.MONTHS.between(updateDateTime, currentTime);

            // 如果相差的月数大于等于1，表示一个月已经过去，需要更新设备状态
            if (monthsBetween >= 1) {
                // 更新设备状态
                device.setStatus(1);
                deviceMapper.updateStatusById(device);
                log.info("设备状态更新成功");

            }
        }
    }
}
